//
//  SearchViewController.m
//  Cooking
//
//  Created by dlios on 15-10-7.
//  Copyright (c) 2015年 ZP.Y. All rights reserved.
//

#import "SearchViewController.h"
#import "AsyncGetConnection.h"
#import "SearchModel.h"
#import "SearchTableViewCell.h"
#import "SearchDetailViewController.h"
#import "PrefixHeader.pch"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#define SETCOLOR(R,G,B) [UIColor colorWithRed:(CGFloat)R/255 green:(CGFloat)G/255 blue:(CGFloat)B/255 alpha:1.0]

@interface SearchViewController ()<UISearchBarDelegate,UITableViewDataSource,UITableViewDelegate,MBProgressHUDDelegate>

{
    int number ;
}

@property(nonatomic ,retain)UISearchBar *search;
@property(nonatomic ,retain)NSMutableArray *tableArray;
@property(nonatomic ,copy)NSString *str;
@property(nonatomic ,retain) UITableView *tableView ;
@property (retain, nonatomic) MBProgressHUD    *HUD;
@property(nonatomic ,retain)UIView *bigView ;



@end

@implementation SearchViewController

- (void)dealloc
{
    [_bigView release];
    [_tableView release];
    [_str release];
    [_HUD release];
    [_tableArray release];
    [_search release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.tableArray = [NSMutableArray array];
        number = 1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    [self creatTableView];
    [self creatSearch];
    [self hotSearch];
    // 下拉刷新
    [self.tableView  addHeaderWithCallback:^{
              [self startConnect];
        number = 1;
    }];
    // 上拉加载
    [self.tableView addFooterWithCallback:^{
        number  ++;
        NSString *numberStr = [NSString stringWithFormat:@"%d",number];
        [_search resignFirstResponder];
        self.str = self.search.text;
        self.str = [self.search.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        // 网络请求
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        // page=1&methodName=SearchDishes&size=10&keyword=%E7%89%9B%E8%82%89&version=4.02&
        [dic setObject:numberStr forKey:@"page"];
        [dic setObject:@"SearchDishes" forKey:@"methodName"];
        [dic setObject:self.str forKey:@"keyword"];
        [dic setObject:@"4.02" forKey:@"version"];
        
        [AsyncGetConnection asyncPOSTConnectionWithURL:@"http://api.izhangchu.com" parameters:dic block:^(NSData *data) {
            [self.bigView removeFromSuperview];
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *dic1 = [dic objectForKey:@"data"];
            NSArray *arr = [dic1 objectForKey:@"data"];
            for (NSDictionary *dic2 in arr) {
                SearchModel *model = [[SearchModel alloc]init];
                [model setValuesForKeysWithDictionary:dic2];
                model.description1 = [dic2 objectForKey:@"description"];
                //            [self.tableArray addObject:dic2];
                
                [self.tableArray addObject:model];
            }
            [self.tableView reloadData];
            [_HUD hide:YES];
            [self.tableView footerEndRefreshing];
        }];
        self.tableView.hidden = NO;

        
    }];
    
}

-(void)creatSearch
{
    self.search = [[UISearchBar alloc]initWithFrame:CGRectMake(40, 10, 300, 0)];
//    search.layer.borderWidth = 0.4;
    _search.layer.cornerRadius = 5;
    _search.placeholder = @"点击搜索";
    self.search.delegate = self;
    self.navigationItem.titleView = _search;
}
-(BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = YES; // 显示取消键
    for (id mm in [searchBar subviews]) {
        if ([mm isKindOfClass:[UIButton class]]) {
             UIButton *cancel = (UIButton *)mm;
        [cancel setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    NSLog(@"开始,编辑");
    return YES;
}

-(void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    self.search.text = @""; // 清除文字
    [self.search resignFirstResponder]; //成为第一响应,搜索
}

// 结束编辑取消编辑状态
-(void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    //加载等待
    [self creatLoad];
//    [_HUD hide:NO];
}
// 创建加载图案
-(void)creatLoad
{
    self.HUD = [[MBProgressHUD alloc] init];
    _HUD = [[MBProgressHUD showHUDAddedTo:self.view animated:YES] retain];
    _HUD.delegate = self;
    _HUD.backgroundColor = [UIColor clearColor];
    _HUD.detailsLabelText = @"努力加载中...";
    _HUD.dimBackground = YES;

}

-(void)hotSearch
{
    NSMutableArray *arr = [NSMutableArray array];
    arr = [@[@"玉米",@"鱼",@"牛肉",@"薯片",@"白菜",@"早餐",@"火锅"] mutableCopy];

    self.bigView = [[UIView alloc]initWithFrame:CGRectMake(0, 10, self.view.frame.size.width, 30*arr.count+40)];
    [self.view addSubview:self.bigView];
    
    
    UIView *myView = [[UIView alloc]initWithFrame:CGRectMake(0, 30, self.view.frame.size.width, 30*arr.count)];
    [self.bigView addSubview:myView];
    UILabel *alabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 5, 80, 30)];
    [self.bigView addSubview:alabel];
    alabel.text = @"热门搜索";
    
       for (int i = 0; i < arr.count; i++) {
           UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
           button.frame = CGRectMake(i%4*90+10, i/4*30+15, 85, 25);
           [myView addSubview:button];
           [button setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
           [button setTitle:[arr objectAtIndex:i] forState:UIControlStateNormal];
           button.layer.borderWidth = 0.4;
           button.layer.cornerRadius = 8;
           button.layer.borderColor = [[UIColor redColor] CGColor];
           [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    }


}

-(void)buttonAction:(UIButton *)sender
{
    self.search.text = sender.titleLabel.text;
    // 家在图案
    [self creatLoad];
    //网络请求
    [self startConnect];
    
}
// 搜索的文字
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self startConnect];
}
-(void)startConnect
{
    [_search resignFirstResponder];
    [self.tableArray removeAllObjects];
    self.str = self.search.text;
    self.str = [self.search.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 网络请求
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    // page=1&methodName=SearchDishes&size=10&keyword=%E7%89%9B%E8%82%89&version=4.02&
    [dic setObject:@"1" forKey:@"page"];
    [dic setObject:@"SearchDishes" forKey:@"methodName"];
    [dic setObject:self.str forKey:@"keyword"];
    [dic setObject:@"4.02" forKey:@"version"];
    
    [AsyncGetConnection asyncPOSTConnectionWithURL:@"http://api.izhangchu.com" parameters:dic block:^(NSData *data) {
        [self.bigView removeFromSuperview];
        [self.tableArray removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic1 = [dic objectForKey:@"data"];
        NSArray *arr = [dic1 objectForKey:@"data"];
        for (NSDictionary *dic2 in arr) {
            SearchModel *model = [[SearchModel alloc]init];
            [model setValuesForKeysWithDictionary:dic2];
            model.description1 = [dic2 objectForKey:@"description"];
            //            [self.tableArray addObject:dic2];
            
            [self.tableArray addObject:model];
        }
        [self.tableView reloadData];
        [_HUD hide:YES];
        [self.tableView headerEndRefreshing];
    }];
    self.tableView.hidden = NO;

}

-(void)creatTableView
{
    self.tableView = [[[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-64) style:UITableViewStylePlain]autorelease];
    [self.view addSubview:_tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 120*OffHeight;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.tableArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellName =@"searchtablecell";
    SearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellName];
  if (!cell) {
    cell = [[[SearchTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName]autorelease]
        ;
  }
     SearchModel *model =  [self.tableArray objectAtIndex:indexPath.row];
    cell.text = self.search.text;
     NSMutableAttributedString *dataStr1 = [cell colorData:model.title];
    cell.title.attributedText = dataStr1;
    if (self.tableArray.count != 0) {
        SearchModel *model =  [self.tableArray objectAtIndex:indexPath.row];
      [cell receveModel:[self.tableArray objectAtIndex:indexPath.row]];
        NSLog(@"image = %@",model.image);
  }
       return cell ;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
    SearchDetailViewController *searchDetail = [[[SearchDetailViewController alloc]init]autorelease];
    [searchDetail receveSearchModel:[self.tableArray objectAtIndex:indexPath.row]];
    [self.navigationController pushViewController:searchDetail animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
